define(["css!/Emall/front/css/login_dialog.css",
        "css!/Emall/front/css/styles.css",
    "jquery", "defaultvalue", "form", "layer",
    "validationEngine", "tabify"
],function ($){
	(function ($) {
        var  _loginDialog = {
                generateActivationCodeBtnId:"generateActivationCodeBtn",

                registerBtnId:"registerBtn",

                userloginBtnId:"userloginBtn",

                userLoginForm : "userLoginForm",

                registerForm : "registerForm",
               
                userLoginForm : "userLoginForm",

                activationCodeSendAbleTimes : 3,
                
                options : {},
                
                init:function() {

                	
                		
                	
                        var login_dialog_html =
                        	'	<div id="login_dialog" class="login_dialog" style="display: none;" >'+
                        	'		<div class="fluid" style="position:relative;" id="tab-container">'+
                        	'           <div class="" style="background-color: #FFF; margin: 10px; padding:10px;">'+
                            '           	<div class="tabs mt" id="tabNavDiv">' +
                            '      			    <ul class="tabs ">' +
                            '                       <li class="activeTab" targetDivId="tabb1"><a >注册</a></li>' +
                            '                       <li targetDivId="tabb2"><a>登录</a></li>' +
                            '           	 	</ul>' +
                            '            	</div>' +
                                '			<div class="tab_container">'+
                                '					<!-- tab1 begin-->'+
                                '				<form id="registerForm" name="registerForm" action="reg_mobileRegister" method="post">'+
                                '				    <div class="tab_content registerArea" id="tabb1">'+
                                '				        <div class="formRow">'+
                                '				            <div>'+
                                '					            <label><span class="required">*</span>用户名：</label>'+
                                '					        </div>'+
                                '					        <div class="item">'+
                                '						        <input type="text" name="mobileOrMaill" id="user_mobileOrMail" placeholder="请填写手机或邮箱地址" class="validate[required,custom[phoneOrEmail], ajax[ajaxPhoneOrEmailValidate]" data-prompt-position="inline" data-prompt-target="mobileOrMaill_validate_info"/>'+
                                '						        <span class="tips_icon"></span>'+
                                '					        </div>	'+
                                '					        <div style="clear:both;"></div>	'+
                                '				        </div>'+
                                '					    <div class="tipsArea" id="mobileOrMaill_validate_info"></div>'+
                                '					    <div class="formRow">'+
                                '						    <div>'+
                                '							    <label><span class="required">*</span>授权码：</label>	'+
                                '						    </div>'+
                                '					        <div class="item">'+
                                '					            <input type="text" id="register_authorizationcode" name="user.authorizationcode" style="width:110px;" class="validate[required]" data-prompt-position="inline" data-prompt-target="activationcode_info"/>'+
                                '						        <span class="tips_icon"></span>'+
                                '					        </div>'+
                                '					        <div id="activeCodeLinkDiv">'+
                                '					            <a id="generateActivationCodeBtn" class="validBtn submitBtnDiv bBlue buttonS" href="javascript:void(0);">发送授权码</a>'+
                                '						        <span id="generateActivationCodeInfo"></span>'+
                                '					        </div>'+
                                '					        <div style="clear:both;"></div>'+
                                '					    </div>'+
                                '					    <div class="tipsArea" id="activationcode_info"  ></div>'+
                                '					    <div class="formRow">'+
                                '					        <div>'+
                                '						        <label><span class="required">*</span>创建密码：</label>'+
                                '						    </div>'+
                                '						    <div class="item">'+
                                '						        <input type="password" id="register_password" class="validate[required,minSize[6],maxSize[20]]" data-prompt-position="inline" data-prompt-target="password_info" name="user.password" placeholder="请填写6-20数字或字母"/>'+
                                '							    <span class="tips_icon "></span>'+
                                '						    </div>'+
                                '						    <div style="clear:both;"></div>	'+
                                '						</div>'+
                                '						<div class="tipsArea" id="password_info"  ></div>'+
                                '						<div class="formRow">'+
                                '							<div>'+
                                '								<label><span class="required ">*</span>确认密码：</label>'+
                                '							</div>'+
                                '							<div class="item">'+
                                '							    <input type="password" id="register_passwordConfirm" class="validate[required,minSize[6],maxSize[20],equals[register_password]]" data-prompt-position="inline" data-prompt-target="passwordConfirm_info" name="user.passwordConfirm" />'+
                                '								<span class="tips_icon "></span>'+
                                '							</div>'+
                                '							<div style="clear:both;"></div>'+
                                '						</div>'+
                                '						<div class="tipsArea" id="passwordConfirm_info"  ></div>'+
                                '						<div class="formRow">'+
                                '							<label>&nbsp</label>'+
                                '							<div>'+
                                '							    <a id="registerBtn" class="submitBtnDiv bYellow buttonS registBtn" style="font-size:14px" href="javascript:void(0);">立&nbsp;即&nbsp;注&nbsp;册</a>'+
                                '							</div>'+
                                '						</div>'+
                                '						<div style="clear:both;"></div>'+
                                '						<div class="grid10 " style="margin-top: 10px;">'+
                                '						    <div id="registerAgree_info"  ></div>' +
                                '							<input id="register_agree" type="checkbox" value="" name="register_agree" checked style="vertical-align:middle" class="validate[required]" data-prompt-position="inline" data-prompt-target="registerAgree_info"/>'+
                                '								我已阅读并接受<a href="/Emall/front/agreement_article.html" target="_blank" class="poplink">用户协议</a>'+
                                '						</div>'+
                                '						<div class="clear"></div>'+
                                '					</div>'+
                                '				</form>'+
                                '				<!-- tab1 end-->'+
                                '				<!-- tab2 begin-->'+
                                '				<form id="userLoginForm" name="userLoginForm" action="reg_loginForNewLoginDialog" method="post">'+
                                '				    <div class="tab_content loginArea" id="tabb2">'+
                                '					    <div class="formRow">'+
                                '						   <div class="item">'+
                                '								<span class="username_icon"></span>'+
                                '								<input type="text" class="validate[required, custom[phoneOrEmail]]" name="mobileOrMaill" id="loginMobileOrMaill" placeholder="电子邮箱或手机号" data-prompt-position="inline" data-prompt-target="loginMobileOrMaill_info"/>'+
                                '								<span class="tips_icon"></span>'+
                                '							</div>'+
                                '						</div>'+
                                '					    <div class="tipsArea" id="loginMobileOrMaill_info"></div>'+
                                '						<div class="formRow">'+
                                '							<div class="item">'+
                                '							<span class="password_icon"></span>'+
                                '							<input id="loginPassword" type="password" class="validate[required,minSize[6],maxSize[20]]" name="user.password" placeholder="密码" data-prompt-position="inline" data-prompt-target="loginPassword_info"/>'+
                                '							<span class="tips_icon"></span>'+
                                '							</div>'+
                                '					    </div>'+
                                '					    <div class="tipsArea" id="loginPassword_info"></div>'+
                                '					    <div class="tipsArea" id="loginMessage" class="loginMessage"></div>'+
                                '					    <div class="formRow">'+
                                '						    <div class="widget" style="width:150px;float:left;">'+
                                '							    <label> ' +
                            '                                       <input type="checkbox" name="autologin"'+
                                '										value="true" class="mr5" style="vertical-align:middle"/>一个月内自动登录'+
                                '							    </label>'+
                                '						    </div>'+
                                '						    <div class="widget right" style="width:100px;float:right;margin-right:-15px;">'+
                                '							    <a href="/Emall/front/forget_password.jsp" class="forget_ps" >忘记密码？</a>'+
                                '						    </div>'+
                                '						    <div class="clear"></div>'+
                                '					    </div>'+
                                '					    <div class="formRow">'+
                                '						    <a id="userloginBtn" class="buttonL" href="javascript:void(0);">登&nbsp;&nbsp;&nbsp;&nbsp;录</a>'+
                                '					    </div>'+
                                '					    <div class="formRow" style="margin-top:5px;">'+
                                '						    <span class="ycstel">客服电话：400-855-7878转000</span>'+
                                '					    </div>'+
                                '					    <div class="formRow">'+
                                '						    客服时间：周一到周日，8：30～17：15'+
                                '					    </div>'+
                                '				    </div>'+
                                '			    </form>'+
                                '		        <!-- tab2 end-->'+
                                '		    </div>'+
                                '       </div>' +
                        	'	    </div>'+
                        	'	</div>';

                        $("body").append(login_dialog_html);
                        $('input[placeholder]').placeholder();

                        $('#login_dialog').mytab();
                        $.validationEngine.ajaxConfig = {
                            "ajaxPhoneOrEmailValidate":{
                                "url" : "/Emall/front/reg_phoneOrEmailValidate",
                                "alertTextOk" : "* 此帐号名称可以使用",
                                "alertText" : "* 此名称已被其他人使用",
                                "alertTextLoad" : "* 正在确认帐号名称是否可用"
                            }
                        };
                        var validateOption = {
                            scroll:false,
                            ajaxFormValidation: true,
                            //binded:false,
                            //showArrow:false,
                            //promptPosition:"centerRight",
                            autoHidePrompt : false,
                            maxErrorsPerField:1,
                            showOneMessage:true,
                            addPromptClass:"formError-noArrow formError-text",
                            onFieldSuccess : function (field) {
                            	$(field).next(".tips_icon").removeClass("wrong");
                            	if ($(field).attr("id") != "register_authorizationcode") {
                            		$(field).next(".tips_icon").addClass("right");
                            		
                            	}
                            	if(field && typeof field.attr('data-prompt-target') !== 'undefined' && $('#'+field.attr('data-prompt-target')).length > 0 && $(field).attr("id") == "user_mobileOrMail") {
                            		$('#'+field.attr('data-prompt-target')).css({"background-color":"white","border":"1px solid #86dad5"});
                            	}
                            },
                            onFieldFailure : function (field) {
                            	$(field).next(".tips_icon").removeClass("right");
                            	$(field).next(".tips_icon").addClass("wrong");
                            	if(field &&  typeof field.attr('data-prompt-target') !== 'undefined' && $('#'+field.attr('data-prompt-target')).length > 0 && $(field).attr("id") == "user_mobileOrMail") {
                            		$('#'+field.attr('data-prompt-target')).css({"background-color":"#fff2f2","border":"1px solid #ff8585"});
                            	}
                            },
                            ajaxReturnIsSuccess:function (json) {
                                if (json.result == 'SUCCESS') {
                                    return true;
                                } else {
                                    return false;
                                }
                            }
                        };
                        
                        var loginValidateOption = {
                                scroll:false,
                                ajaxFormValidation: true,
                                //binded:false,
                                //showArrow:false,
                                //promptPosition:"centerRight",
                                autoHidePrompt : false,
                                maxErrorsPerField:1,
                                showOneMessage:true,
                                addPromptClass:"formError-noArrow formError-text",
                                onFieldSuccess : function (field) {
                                	$(field).next(".tips_icon").removeClass("wrong");
                                },
                                onFieldFailure : function (field) {
                                	$(field).next(".tips_icon").addClass("wrong");
                                }
                            };
                        $("#" + _loginDialog.registerForm).validationEngine(validateOption);
                        $("#" + _loginDialog.userLoginForm).validationEngine(loginValidateOption);

                        $("#"+this.generateActivationCodeBtnId).click(this.generateActivationCode);
                        $("#"+this.registerBtnId).click(this.register);
                        $("#"+this.userloginBtnId).click(this.userlogin);
                        _inited = true;
                	
                },

                generateActivationCode :function(){
                    var time = $("#time").text();
                    if (time > 0) {
                        return;
                    }

                    var valid = jQuery("#user_mobileOrMail").validationEngine("validate");
                    if (!valid) {
                        return;
                    }

                    var url = "/Emall/front/reg_sendActiveCode.action?mobileOrMaill="+$("#user_mobileOrMail").val();
                    $.getJSON(
                        url,
                        function(data) {
                            //$("#activeCodeLink_info").html('<a class="buttonS bBlue " href="javascript:generateActivationCode();">再次获取授权码</a>');
                            var result = data.result;
                            if(result == 'SUCCESS'){
                                $("#activeCodeLinkDiv a").html('<span><span id="time">60</span>秒后再次发送</span>');
                                //$("#activeCodeLinkDiv a").removeClass("bBlue");
                                //$("#activeCodeLinkDiv a").addClass("disableColor");
                                var handler = window.setInterval(function() {

                                    var time = $("#time").text();
                                    if (time > 0) {
                                        $("#time").text(time - 1);
                                    } else {
                                        window.clearInterval(handler);
                                        $("#activeCodeLinkDiv a").html('<span>发送授权码</span>');
                                        $("#activeCodeLinkDiv").removeClass("disableColor");
                                        //$("#activeCodeLinkDiv").addClass("bBlue");
                                    }

                                }, 1000);
                            }else{
                                $("#activeCodeLinkDiv").alert("发送失败，请重新获取授权码");
                            }
                        }
                    );
                },

                register : function() {
                    var valid = jQuery("#" + _loginDialog.registerForm).validationEngine("validate");
                    if (!valid) {
                        return;
                    }

                    url = "/Emall/front/reg_register.action";
                    var myOption = {
                        url : url,
                        dataType : "json",
                        type : "post",
                        success : function(data) {
                        	var result = data.result;
                        	var prompt = data.content[0];
                        	if (result == 'SUCCESS') {
                        		if(_loginDialog.options.autoLoginAfterRegister) {
                        			$("#login_dialog #userLoginForm #loginMobileOrMaill").val($("#login_dialog #registerForm #user_mobileOrMail").val());
                        			$("#login_dialog #userLoginForm #loginPassword").val($("#login_dialog #registerForm #register_password").val());
                        			_loginDialog.userlogin();
                        		}
                        		layer.close(_loginDialog._dialogIndex);
                        	} else {
                        		$("#activationcode_info").show();
                        		$("#activationcode_info").html('<span style="color:red">' +prompt +'</span>');
                        		var originalVal = $("#register_authorizationcode").val();
                        		$("#register_authorizationcode").keydown(function () {
                        			if (originalVal != $(this).val()) {
                        				$("#activationcode_info").html("");
                        				$("#activationcode_info").hide();
                        			}
                        		});
                        	}
                        }
                    };
                    
                    $("#" + _loginDialog.registerForm).ajaxSubmit(myOption);
                    
                },

                _dialogIndex : "",

                userlogin : function(){
                	 var valid = jQuery("#" + _loginDialog.userLoginForm).validationEngine("validate");
                     if (!valid) {
                         return;
                     }
                     
                    var myOption = {
                        url : "/Emall/front/reg_loginForNewLoginDialog.action",
                        type : "post",
                        success : function(data) {
                            var result = data.result;
                            var content = data.content[0];
                            if (result == 'SUCCESS') {
                                layer.close(_loginDialog._dialogIndex);
                                _loginDialog.options.afterLoginSuccess();
                            } else if (result == 'FAIL'){
                            	$("#loginMessage").show();
                                $("#loginMessage").html('<span style="color:red">' + content +'</span>');
                                
                                var originalEmailOrMobile = $("#loginMobileOrMaill").val();
                                
                                var password = $("#loginPassword").val();
                               
                                $("#loginMobileOrMaill").keydown(function () {
                        			if (originalEmailOrMobile != $(this).val()) {
                        				$("#loginMessage").html("");
                        				$("#loginMessage").hide();
                        			}
                        		});
                                
                                $("#loginPassword").keydown(function () {
                        			if (password != $(this).val()) {
                        				$("#loginMessage").html("");
                        				$("#loginMessage").hide();
                        			}
                        		});
                            }
                        },
                        dataType:"json"
                    };
                    $("#" + _loginDialog.userLoginForm).ajaxSubmit(myOption);
                },
                
                hideDialog : function () {
                	layer.close(_loginDialog._dialogIndex);
                },
                
                showDialog : function(){
                    //清空验证提示信息及表单中的填写的内容
                    $("#" + _loginDialog.registerForm).validationEngine("hideAll");
                    $(".tips_icon").removeClass("wrong");
                    $(".tips_icon").removeClass("right");
                    $("#" + _loginDialog.registerForm + " input").val("").removeClass("error");
                    $("#" + _loginDialog.userLoginForm + " input").val("").removeClass("error");

                    _loginDialog._dialogIndex = $.layer({
                        type : 1,
                        shade : [0],
                        area : ['auto', 'auto'],
                        title : false,
                        border : [0],
                        page : {dom : '#login_dialog'}
                    });
                }
            };
            
        	_loginDialog.init();
        	
        	$.loginDialog = {
        		showDialog : _loginDialog.showDialog,
	     		hideDialog : _loginDialog.hideDialog,
	     		setOptions : function (options) {
	     			_loginDialog.options = $.extend(_loginDialog.options, options);
	     		}
	        }; 
        	 
	        $.fn.extend({
	            //插件名称
	            loginDialog: function (options) {
	
	                //参数和默认值
	                var defaults = {
	                	autoShowDialog : false,
	                	autoLoginAfterRegister : true,
	                	isShowDialog : function () {return true;},
	                	afterLoginSuccess : function () {}
	                };
	
	                var options = _loginDialog.options = $.extend(defaults, options);
	                
	                	
	                return this.each(function () {
	                	
	                    var showDialogBt = this;
	                    
	                    if (options.autoShowDialog) {
	                    	$(showDialogBt).click(function () {
	                    		if (options.isShowDialog()) {
	                    			_loginDialog.showDialog();
	                    		}
	                    	});
	                    }
	                });
	            }
	        });
        })(jQuery);
	});
